﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;

namespace RDS.Core
{
    /// <summary>
    /// 通用对象池
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public sealed class ObjectPool<T> : IDisposable, IObjectPoolable<T> where T : class, new()
    {
        private readonly Queue<T> _pool = new Queue<T>();
        private readonly object _lock = new object();
        //private readonly ConcurrentBag<T> _objects;
        //private readonly Func<T> _objectGenerator;
        private readonly int _maxSize;

        public ObjectPool(int maxSize = 10) => _maxSize = maxSize;

        public int MinObjCount => throw new NotImplementedException();

        public int MaxObjCount => throw new NotImplementedException();

        public int CurObjCount => throw new NotImplementedException();

        public int IdleObjCount => throw new NotImplementedException();

        public event CallBackObjPool PoolShrinked;
        public event CallBackObjPool MemoryUseOut;

        /// <summary>
        /// 资源释放
        /// </summary>
        public void Dispose()
        {
            
        }

        public bool Initialize(Type objType, object[] cArgs, int minNum, int maxNum)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 借出对象
        /// </summary>
        /// <returns></returns>
        public T Rent()
        {
            lock (_lock)
            {
                return _pool.Count > 0 ? _pool.Dequeue() : new T();
            }
        }

        /// <summary>
        /// 归还对象
        /// </summary>
        /// <param name="item"></param>
        public void Return(T item)
        {
            lock (_lock)
            {
                if (_pool.Count < _maxSize)
                {
                    // 重置对象状态（需根据具体类型实现）
                    if (item is IResetable resettable)
                        resettable.Reset();
                    _pool.Enqueue(item);
                }
            }
        }

        public void Return(int objHashCode)
        {
            throw new NotImplementedException();
        }
    }

    // 状态重置接口
    public interface IResetable
    {
        void Reset();
    }
}
